// index.js
Page({
  data: {
    username: '',
    address: '',
    name: '',
    longitude: 0,
    latitude: 0,
    image: '/images/icon/add.png'
  },

  onLoad() {
    this.setData({
      username: getApp().globalData.wxusername
    })
    var that = this
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          longitude: res.longitude,
          latitude: res.latitude
        })
        wx.request({
          url: 'https://apis.map.qq.com/ws/geocoder/v1/',
          data: {
            key: '6OSBZ-7ZSW4-UMWU5-K7X6V-VIGYT-W5F7V',
            location: that.data.latitude + ',' + that.data.longitude
          },
          success: function (res) {
            that.setData({
              address: res.data.result.address
            })
          }
        });
      }
    })
  },

  chooseImage: function () {
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        const newImage = res.tempFiles[0].tempFilePath;
        that.setData({
          image: newImage
        })
      }
    })
  },

  goDispatchApply() {
    // 判断是否已传入图片
    var ifok = false
    var errmsg = ''
    // 判断图片是否符合要求
    if (this.data.image == '/images/icon/add.png') {
      ifok = true
      errmsg = '请上传一张此路段图片！'
    }
    // 综合判断
    if (ifok) {
      wx.showModal({
        title: '发送失败',
        content: errmsg,
        showCancel: false
      })
      return
    }
    // 发送申请调度请求
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定要申请调度吗？',
      complete: (res) => {
        if (res.cancel) {}
        if (res.confirm) {
          wx.showLoading({
            title: '正在加载...'
          });
          // 发起网络请求，下载图片内容
          const imgBehind = that.data.image.split('.')
          wx.downloadFile({
            url: that.data.image,
            success: (res) => {
              if (res.statusCode === 200) {
                // 将本地图片数据转换成 base64 编码
                wx.getFileSystemManager().readFile({
                  filePath: res.tempFilePath,
                  encoding: 'base64',
                  success: (res) => {
                    wx.request({
                      url: getApp().globalData.commonIP + '/bikeRequest/applyDispatch',
                      method: 'POST',
                      header: {
                        'content-type': 'application/json', // 默认值
                        'token': wx.getStorageSync('token')
                      },
                      data: {
                        nickName: wx.getStorageSync('nickName'),
                        requestType: '单车调度',
                        locName: that.data.address,
                        locImg: ["data:image/" + imgBehind[imgBehind.length - 1] + ";base64," + res.data]
                      },
                      success: res => {
                        wx.hideLoading();
                        if (res.data.msg == "token过期，请重新登录" || res.data.msg == "token失效，请重新登录" || res.data.msg == "无效签名，请重新登录" || res.data.msg == "token算法不一致，请重新登录") {
                          wx.showModal({
                            title: '提示',
                            content: res.data.msg,
                            showCancel: false,
                            complete: (res) => {
                              if (res.cancel) {

                              }

                              if (res.confirm) {
                                // 重置全局变量和去除缓存
                                getApp().globalData.wxusername = ''
                                getApp().globalData.wxuseravatar = ''
                                wx.removeStorageSync('nickName')
                                wx.removeStorageSync('avatarUrl')
                                wx.removeStorageSync('token')

                                wx.switchTab({
                                  url: '/pages/index/index'
                                })
                              }
                            }
                          })
                          return
                        }
                        wx.showModal({
                          title: '提示',
                          content: res.data.msg,
                          showCancel: false
                        })
                      }
                    })
                  },
                  fail: (error) => {
                    console.error('Error:', error);
                  }
                });
              }
            },
            fail: (error) => {
              console.error('Error:', error);
            }
          });
        }
      }
    })
  }

})